package com.thinkingstar.iads.cs.sys.controller;
import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Chain;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.ViewModel;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.alibaba.druid.proxy.jdbc.JdbcParameter.TYPE;
import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.cs.sys.entity.SysMajor;
import com.thinkingstar.iads.cs.sys.entity.SysResource;
import com.thinkingstar.iads.cs.sys.entity.SysRole;
import com.thinkingstar.iads.cs.sys.entity.SysRoleResource;
import com.thinkingstar.iads.cs.sys.entity.SysUser;
import com.thinkingstar.iads.datacenter.entity.dao.DaoDcProjectSysUser;
import org.nutz.mvc.annotation.Filters;
import javax.servlet.http.HttpSession;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.util.Context;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.crypto.hash.Sha256Hash;
/**
 * 
 * @author Administrator
 *
 */
@IocBean
@At("/resource")
@Filters({@By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class)})
public class IndexModule{
	
	private static final String PATH = "beetl:/index/";
	private static final String UNAUTHORIZED_PATH = "beetl:/sys/";
	
	private static final String TOP_RES_ID = "0";
	
    @Inject
    protected Dao dao;
    
    @Inject
    protected DaoDcProjectSysUser daoDcProjectSysUser;

    @At
    public void dolock(HttpServletRequest req, HttpSession session) {
        session.setAttribute("validate", "openLockWindow();");
    }
    
    @At
    // @Ok("vm:template.private.lock")
    public void lock(HttpServletRequest req, HttpSession session) {
    }
    
    /**
     * 获取登录用户的下级菜单栏
     * @return
     */
    @At("/childrenResource")
    @Ok("json")
    public List <SysResource> getResourceByParentId(@Param("res_id") String resource_id,
    		HttpServletRequest request , HttpSession session){
    	List <SysResource> resource_list = new ArrayList<>();
    	SysUser user = (SysUser)session.getAttribute("userSession");
    	List <String> resource_ids = user.getReslist();
    	List <Integer> role_list = user.getRolelist();
    	List <Integer> major_list = user.getMajorList();
    	//判断是否是系统管理员
    	Boolean is_admin = user.getSysrole();
    	if(is_admin){
    		//拥有全部权限
    		resource_list = daoDcProjectSysUser.getResourceByAdminAndParentResId(resource_id);
    		for(SysResource sysResource : resource_list){
    			List <SysResource> children_res_list = new ArrayList<>();
    			children_res_list = daoDcProjectSysUser.getResourceByAdminAndParentResId(sysResource.getId());
    			sysResource.setResource_list(children_res_list);
    		}
    	}else{
    		//获取二级菜单
    		resource_list = daoDcProjectSysUser.getResourceByUserIdAndResId(resource_ids,resource_id);
    		for(SysResource sysResource : resource_list){
    			//获取三级菜单
    			List <SysResource> children_res_list = new ArrayList<>();
    			children_res_list = daoDcProjectSysUser.getResourceByUserIdAndResId(resource_ids,sysResource.getId());
    			sysResource.setResource_list(children_res_list);
    		}
    	}
    	return resource_list;
    }
    
    /**
     * 获取登录用户的顶级菜单栏
     * @return
     */
    @At("/parentResource")
    @Ok("json")
    public List <SysResource> getResourceByTopId(HttpServletRequest request , HttpSession session){
    	SysUser user = (SysUser)session.getAttribute("userSession");
    	List <String> resource_ids = user.getReslist();
    	List <Integer> role_list = user.getRolelist();
    	List <Integer> major_list = user.getMajorList();
    	List <SysResource> resource_list = new ArrayList<>();
    	//判断是否是系统管理员
    	Boolean is_admin = user.getSysrole();
    	if(is_admin){
    		//拥有全部以及菜单
    		resource_list = daoDcProjectSysUser.getResourceByAdminAndParentResId(TOP_RES_ID);
    	}else{
    		//获取所有菜单
    		resource_list = daoDcProjectSysUser.getResourceByUserIdAndResId(resource_ids,TOP_RES_ID);
    	}
    	return resource_list;
    }
    
    /**
     * 用户登录
     * @param req
     * @param session
     */
    @At("/index")
    @Ok(PATH+"index.html")
    public NutMap index(@Param("parent_id") String parent_id , @Param("children_id") String children_id ,HttpServletRequest req, HttpSession session) {
    	NutMap nutMap = new NutMap().addv("parent_id", parent_id).addv("children_id", children_id);
    	return nutMap;
    }


	/**
	 *  无权限访问时的错误页面
	 * @param req
	 * @param session
	 * @return
	 */
	@At("/unauthorized")
	@Ok("re")
	public String unauthorized(HttpServletRequest req, HttpSession session) {
		return UNAUTHORIZED_PATH+"401.html";
	}

	/**
	 *  权限ajax用于js控制页面动态生产的按钮 初步的思路是：
	 *       1.   用户登录以后由shiro管理 和 存储用户的权限信息   SecurityUtils.getSubject()   可以得到当前用户   user.getReslist()  or  user.getRoles()
	 *       得到用户的当前角色和权限.
	 *       2.   在相关页面加载的时候  通过本方法获得权限信息到前端页面
	 *       3.    前端页面  $(document).ready(function () {
	 *                                            //判断角色
	 *                                             	  judgeAuthority();
	 *                                 });
	 *
	 *                function judgeAuthority(){
	 *                        $.ajax({
	 *                             type: "post",
	 *                             url: "",
	 *                            contentType: 'application/json;charset=utf-8',
	 *                            success: function (data) {
	 *                                 for(var i=0;i<data.length;i++){
	 *                                     if(data[i]=="admin"){
	 *                                          $(".admin").css("display","block");
	 *                                     }
	 *                                  }
	 *                              }
	 *                          })
	 *                 }
	 *             4.  页面在动态生成的按钮的class中 使用  display ：none    在进行角色权限判断后   如果有权限则显示 没有权限则是隐藏状态 如果需要
	 *                  也可以给按钮加入disabled 属性   有权限后   将该属性remove掉.
	 * @param req
	 * @param session
	 * @return
	 */
	@At("/rolesAddPerms")
	@Ok("raw")
	public String rolesAddPerms(HttpServletRequest req, HttpSession session) {
		Subject subject= SecurityUtils.getSubject();
		SimpleAuthorizationInfo user =  (SimpleAuthorizationInfo) subject.getSession().getAttribute("authorizationInfo");
		NutMap permList=new NutMap();
		permList.put("roles",user.getRoles());
		permList.put("perms",user.getStringPermissions());
		return Json.toJson(permList);
	}
}
